/*
红包流程：
发：
判断余额——————》发送红包————————》发送记录————————————》完成
收：
判断允许领取————————》领取红包————————》领取记录————————》完成
*/
var express = require('express');
var router = express.Router();

/* GET home page. */
router.post('/send2user', function (req, res, next) {
    /*发送红包给用户 */
    /* from_uid：发红包的人的uid
    from_id:发红包的人的id
    to_uid:收红包的人的uid
    to_id:收红包人的id
    type:红包类型，默认1，普通红包
    account:总金额 */


    /*  
    res：{
        statust:-1//余额不足
    }
     */
    var str = 'from_id:' + req.session.m_id + 'to_id:' + req.body.to_id + 'type:' + req.body.type + 'account:' + req.body.account + 'reason:' + req.body.reason;
    str = str.toString();
    var md5Str = md5str(str);
    if (md5Str == req.headers.singy) {
        sqlQuery('member_table', '*', {
            member_id: req.session.m_id
        }, function (result) {
            if (result[0].member_money - req.body.account >= 0) {
                //如果金额足够，就开始发红包的流程
                let task1 = sqlUpdateStr('member_table', {
                    member_money: result[0].member_money - req.body.account
                }, 'where member_id=' + req.session.m_id); //扣除金额
                var token = getToken(); //定义Token 
                let task2 = sqlInsStr('red2user', {
                    from_id: req.session.m_id,
                    to_id: req.body.to_id,
                    register_time: getNowTime(),
                    invalid_time: getNowTime() + 3600 * 24,
                    account: req.body.account,
                    type: 1,
                    token: token,
                    reason: req.body.reason
                }) //发红包
                let task3 = sqlInsStr('member_money', {
                    type: 1,
                    money_sess: getNowTime() + generateMixed(6),
                    money_id: req.session.m_id,
                    money_add: (0 - req.body.account),
                    money_reason: language.money_reason[0],
                    money_left: result[0].member_money - req.body.account,
                    modify_id: req.session.m_id,
                    modify_ip: getClientIp(req),
                    register_date: getNowTime(),
                    approval_date: getNowTime()
                })
                Transaction([task1, task2, task3], function (result) {
                    //事务结束，返回false 和 true   
                    if (result.length > 0) { //发送成功了
                        var respond = {
                            ret: 200,
                            data: {
                                token: token,
                                uid: result[1].insertId,
                                status: 1 //发送成功
                            }
                        }
                        res.json(respond);
                    } else {
                        var respond = {
                            ret: 200,
                            data: {
                                status: 0 //发送失败
                            }

                        }
                        res.json(respond);
                    }
                })

            } else {
                //余额不足
                var respond = {
                    ret: 200,
                    data: {
                        status: -1 //余额不足
                    }

                }
                res.json(respond);
            }
        })
    } else {
        var respond = {
            ret: 201,
            data: {}
        }
        res.json(respond);
    }
}); //发送对用户的红包

router.post('/send2group', function (req, res, next) {
    /*发送红包给用户 */
    /*

    from_id:发红包的人的id
    to_id:收红包群的id
    type:红包类型，默认1，普通红包，2为手气红包
    num:红包的数量
    account:总金额 */


    /*  
    res：{
        statust:-1//余额不足
    }
     */
    var str = 'from_id:' + req.session.m_id + 'to_id:' + req.body.to_id + 'type:' + req.body.type + 'num:' + req.body.num + 'account:' + req.body.account + 'reason:' + req.body.reason;
    str = str.toString();
    console.log(str);
    var md5Str = md5str(str);
    console.log(md5Str);
    if (md5Str == req.headers.singy) {
        sqlQuery('member_table', '*', {
            member_id: req.session.m_id
        }, function (result) {
            if (result[0].member_money - req.body.account >= 0) {
                //如果金额足够，就开始发红包的流程
                let task1 = sqlUpdateStr('member_table', {
                    member_money: result[0].member_money - req.body.account
                }, 'where member_id=' + req.session.m_id); //扣除金额
                var token = getToken(); //定义Token 
                let task2 = sqlInsStr('red2group', {
                    from_id: req.session.m_id,
                    to_id: req.body.to_id,
                    register_time: getNowTime(),
                    invalid_time: getNowTime() + 3600 * 24,
                    account: req.body.account,
                    account_left: req.body.account,
                    num: req.body.num,
                    num_left: req.body.num,
                    type: req.body.type,
                    token: token,
                    reason: req.body.reason
                }) //发红包
                let task3 = sqlInsStr('member_money', {
                    type: 1,
                    money_sess: getNowTime() + generateMixed(6),
                    money_id: req.session.m_id,
                    money_add: (0 - req.body.account),
                    money_reason: language.money_reason[0],
                    money_left: result[0].member_money - req.body.account,
                    modify_id: req.session.m_id,
                    modify_ip: getClientIp(req),
                    register_date: getNowTime(),
                    approval_date: getNowTime()
                }) //插入资金明细
                Transaction([task1, task2, task3], function (result) {
                    //事务结束，返回false 和 true   
                    if (result.length > 0) { //发送成功了
                        var respond = {
                            ret: 200,
                            data: {
                                token: token,
                                uid: result[1].insertId,
                                status: 1 //发送成功
                            }
                        }
                        res.json(respond);
                    } else {
                        var respond = {
                            ret: 200,
                            data: {
                                status: 0 //发送失败
                            }

                        }
                        res.json(respond);
                    }
                })

            } else {
                //余额不足
                var respond = {
                    ret: 200,
                    data: {
                        status: -1 //余额不足
                    }

                }
                res.json(respond);
            }
        })
    } else {    
        var respond = {
            ret: 201,
            data: {}
        }
        res.json(respond);
    }
}); //发送对群聊的红包

router.post('/receive2user', function (req, res, next) {
    /* 
       receive_id:领取人的ID
       receive_red_uid:领取的红包的UID
       receive_red_token:领取的红包的token
    */
    var str = 'receive_id:' + req.session.m_id + 'receive_red_uid:' + req.body.receive_red_uid + 'receive_red_token:' + req.body.receive_red_token;
    str = str.toString();
    var md5Str = md5str(str);
    if (md5Str == req.headers.singy) {
        //验证签名成功，第一步先看看红包还能不能领取
        sqlQuery('red2user', '*', {
            to_id: req.session.m_id,
            uid: req.body.receive_red_uid,
            token: req.body.receive_red_token
        }, function (result) {
            if (result.length.length == 0) {
                //查不到这个红包
                var respond = {
                    ret: 200,
                    data: {
                        status: -3 //查不到这个红包
                    }
                }
                res.json(respond);
                return;
            }
            if (result[0].status != 0 && result[0].invalid_time < getNowTime()) {
                //红包已过期
                sqlQuery('red_log', '*', {
                    receive_red_token: req.body.receive_red_token,
                    receive_red_uid: req.body.receive_red_uid,
                    red_type: 1
                }, function (result) {
                    var respond = {
                        ret: 200,
                        data: {
                            status: -1, //红包已过期
                            receive_data: result
                        }
                    }
                    res.json(respond);
                    return;
                })
            }
            if (result[0].status == 0) {
                //红包已领取
                //返回记录
                sqlQuery('red_log', '*', {
                    receive_red_token: req.body.receive_red_token,
                    receive_red_uid: req.body.receive_red_uid,
                    red_type: 1
                }, function (result) {
                    var respond = {
                        ret: 200,
                        data: {
                            status: 0, //红包已领取
                            receive_data: result
                        }
                    }
                    res.json(respond);
                    return;
                })
            } //红包已领取
            if (result[0].status > 0 && result[0].invalid_time > getNowTime()) {
                //红包可以领取
                //返回记录

                /*
                1.领取红包，改变红包的状态
                2.领取红包的人的余额增加
                3.领取人的资金明细变动
                4.领取红包的记录
                */
                sqlQuery('member_table', '*', {
                    member_id: req.session.m_id
                }, function (result1) {
                    //获取收红包的人的信息
                    let task1 = sqlUpdateStr('red2user', {
                        status: 0,
                        invalid_time: getNowTime()
                    }, 'where uid=' + req.body.receive_red_uid + ' and token="' + req.body.receive_red_token + '"');

                    let task2 = sqlUpdateStr('member_table', {
                        member_money: result[0].account + result1[0].member_money
                    }, 'where member_id=' + req.session.m_id); //增加金额

                    let task3 = sqlInsStr('member_money', {
                        type: 2,
                        money_sess: getNowTime() + generateMixed(6),
                        money_id: req.session.m_id,
                        money_add: result[0].account,
                        money_reason: language.money_reason[1],
                        money_left: result1[0].member_money + result[0].account,
                        modify_id: req.session.m_id,
                        modify_ip: getClientIp(req),
                        register_date: getNowTime(),
                        approval_date: getNowTime()
                    })

                    let task4 = sqlInsStr('red_log', {
                        receive_id: req.session.m_id,
                        receive_red_uid: req.body.receive_red_uid,
                        receive_red_token: req.body.receive_red_token,
                        receive_account: result[0].account,
                        receive_time: getNowTime(),
                        red_type: 1
                    })
                    Transaction([task1, task2, task3, task4], function (result2) {
                        if (result2.length > 0) {
                            sqlQuery('red_log', '*', {
                                receive_red_uid: req.body.receive_red_uid,
                                red_type: 1
                            }, function (result3) {
                                var respond = {
                                    ret: 200,
                                    data: {
                                        status: 1, //领取成功
                                        receive_data: result3
                                    }
                                }
                                res.json(respond);
                                return;
                            })

                        } else {
                            var respond = {
                                ret: 200,
                                data: {
                                    status: -2, //事务出错
                                }
                            }
                            res.json(respond);
                            return;
                        }

                    });
                })

            }

        });
    } else {
        var respond = {
            ret: 201,
            data: {}
        }
        res.json(respond);
    }
}) //领取私人红包

router.post('/receive2group', function (req, res, next) {
    /* 
       receive_id:领取群的ID
       receive_red_uid:领取的红包的UID
       receive_red_token:领取的红包的token
    */
    var str = 'receive_id:' + req.body.receive_id + 'receive_red_uid:' + req.body.receive_red_uid + 'receive_red_token:' + req.body.receive_red_token;

    str = str.toString();
    var md5Str = md5str(str);
    if (md5Str == req.headers.singy) {
        //验证签名成功，第一步先看看红包还能不能领取
        sqlQuery('red2group', '*', {
            to_id: req.body.receive_id,
            uid: req.body.receive_red_uid,
            token: req.body.receive_red_token
        }, function (result) {
            if (result.length.length == 0) {
                //查不到这个红包
                var respond = {
                    ret: 200,
                    data: {
                        status: -3 //查不到这个红包
                    }
                }
                res.json(respond);
                return;
            }
            if (result[0].status != 0 && result[0].invalid_time < getNowTime()) {
                //红包已过期
                sqlQuery('red_log', '*', {
                    receive_red_token: req.body.receive_red_token,
                    receive_red_uid: req.body.receive_red_uid,
                    red_type: 2
                }, function (result) {
                    var respond = {
                        ret: 200,
                        data: {
                            status: -1, //红包已过期
                            receive_data: result
                        }
                    }
                    res.json(respond);
                    return;
                })
            }
            if (result[0].status == 0) {
                //红包已领取
                //返回记录
                sqlQuery('red_log', '*', {
                    receive_red_token: req.body.receive_red_token,
                    receive_red_uid: req.body.receive_red_uid,
                    red_type: 2
                }, function (result) {
                    var respond = {
                        ret: 200,
                        data: {
                            status: 0, //红包已领取
                            receive_data: result
                        }
                    }
                    res.json(respond);
                    return;
                })
            } //红包已领取完
            if (result[0].status > 0 && result[0].invalid_time > getNowTime()) {
                
                sqlQuery('red_log', '*', {
                        receive_red_token: req.body.receive_red_token,
                        receive_red_uid: req.body.receive_red_uid,
                        red_type: 2,
                        receive_id: req.session.m_id
                    }, function (result4) {
                        if (result4.length <= 0) {
                                //查到已经领了多少个
                                    //红包可以领取
                                    //返回记录

                                /*
                                1.领取红包，改变红包的状态
                                2.领取红包的人的余额增加
                                3.领取人的资金明细变动
                                4.领取红包的记录
                                */

                                let receiveAccount=0.00;//红包领取的金额
                                
                                if(result[0].type==1){
                                    //普通紅包
                                    receiveAccount=parseFloat(result[0].account)/parseFloat(result[0].num);
                                }
                                else{
                                    //手气红包
                                    if(0>=result[0].num_left){
                                        
                                        //领取的数量超过红包的了
                                        
                                    }
                                    else if(1==result[0].num_left){
                                        //最后一个红包了
                                        receiveAccount=result[0].account_left;
                                        
                                    }
                                    else if(1<result[0].num_left){
                                        //随机红包
                                        receiveAccount=toFloat(Math.random()*(result[0].account_left/2)); 
                                    }
                                }
                                if(receiveAccount>0){
                                    sqlQuery('member_table', '*', {
                                        member_id: req.session.m_id
                                    }, function (result1) {
                                        //获取收红包的人的信息
                                        let task1 = sqlUpdateStr('red2group', {
                                            status: result[0].account_left==receiveAccount?0:1,
                                            invalid_time: result[0].account_left==receiveAccount?getNowTime():result[0].invalid_time,
                                            num_left:result[0].num_left-1
                                        }, 'where uid=' + req.body.receive_red_uid + ' and token="' + req.body.receive_red_token + '"');
        
                                        let task2 = sqlUpdateStr('member_table', {
                                            member_money: result[0].account + result1[0].member_money
                                        }, 'where member_id=' + req.session.m_id); //增加金额
        
                                        let task3 = sqlInsStr('member_money', {
                                            type: 2,
                                            money_sess: getNowTime() + generateMixed(6),
                                            money_id: req.session.m_id,
                                            money_add: result[0].account,
                                            money_reason: language.money_reason[1],
                                            money_left: result1[0].member_money + result[0].account,
                                            modify_id: req.session.m_id,
                                            modify_ip: getClientIp(req),
                                            register_date: getNowTime(),
                                            approval_date: getNowTime()
                                        })
        
                                        let task4 = sqlInsStr('red_log', {
                                            receive_id: req.session.m_id,
                                            receive_red_uid: req.body.receive_red_uid,
                                            receive_red_token: req.body.receive_red_token,
                                            receive_account: result[0].account,
                                            receive_time: getNowTime(),
                                            red_type: 2
                                        })
                                        Transaction([task1, task2, task3, task4], function (result2) {
                                            if (result2.length > 0) {
                                                sqlQuery('red_log', '*', {
                                                    receive_red_uid: req.body.receive_red_uid,
                                                    red_type: 2
                                                }, function (result3) {
                                                    var respond = {
                                                        ret: 200,
                                                        data: {
                                                            status: 1, //领取成功
                                                            receive_data: result3
                                                        }
                                                    }
                                                    res.json(respond);
                                                    return;
                                                })
        
                                            } else {
                                                var respond = {
                                                    ret: 200,
                                                    data: {
                                                        status: -2, //事务出错
                                                    }
                                                }
                                                res.json(respond);
                                                return;
                                            }
        
                                        });
                                    })
                                }
                                else
                                {
                                    sqlQuery('red_log', '*', {
                                        receive_red_token: req.body.receive_red_token,
                                        receive_red_uid: req.body.receive_red_uid,
                                        red_type: 2
                                    }, function (result) {
                                        var respond = {
                                            ret: 200,
                                            data: {
                                                status: 0, //红包已领取
                                                receive_data: result
                                            }
                                        }
                                        res.json(respond);
                                        return;
                                    })
                                }
                            
                           
                        }
                        else {
                            
                            sqlQuery('red_log', '*', {
                                receive_red_token: req.body.receive_red_token,
                                receive_red_uid: req.body.receive_red_uid,
                                red_type: 2
                            }, function (result) {
                                var respond = {
                                    ret: 200,
                                    data: {
                                        status: 0, //红包已领取
                                        receive_data: result
                                    }
                                }
                                res.json(respond);
                                return;
                            })
                            
                        }
                    }
                )}

        });
    } 
    else {
        var respond = {
            ret: 201,
            data: {}
        }
        res.json(respond);
    }
}) //领取群聊红包

router.post('/checkred', function (req, res, next) {
    /* 
        from_id:来自谁发的，一般都只能看自己发的
        receive_red_uid:领取的红包的UID
        receive_red_token:领取的红包的token
    */
    var str = 'from_id:' + req.session.m_id + 'receive_red_uid:' + req.body.receive_red_uid + 'receive_red_token:' + req.body.receive_red_token;
    str = str.toString();
    var md5Str = md5str(str);
    if (md5Str == req.headers.singy) {
        sqlQuery('red2user', ' uid,token,from_id,to_id ', {
            from_id: req.session.m_id,
            uid: req.body.receive_red_uid,
            token: req.body.receive_red_token
        }, function (result) {
            if (result.length == 0) {
                var respond = {
                    ret: 200,
                    data: {
                        status: -1 //查不到这个红包
                    }
                }
                res.json(respond);
                return;
            }
            sqlQuery('red_log', '*', {
                receive_red_uid: result[0].uid,
                receive_red_token: result[0].token
            }, function (result1) {
                var respond = {
                    ret: 200,
                    data: {
                        status: 1, //查询成功
                        receive_data: result1 //查询记录
                    }
                }
                res.json(respond);
                return;
            })
        });
    } else {
        var respond = {
            ret: 201,
            data: {}
        }
        res.json(respond);
    }
})
module.exports = router;